package modes

import (
	"fmt"
	"time"
)

/*考试记录*/

type ExamLog struct {
	Id       int64  `json:"exam_id"`                         //id
	UId      int64  `json:"exam_uid" xorm:"uid"`             //学员ID
	SId      int64  `json:"exam_sid" xorm:"sid"`             //科目id
	NId      int64  `json:"exam_nid" xorm:"nid"`             //套题ID
	CId      int64  `json:"exam_cid" xorm:"cid"`             //班型ID
	Name     string `json:"exam_name" xorm:"name"`           //试卷名称
	Total    int    `json:"exam_total" xorm:"total"`         //得分总数
	Rate     int    `json:"exam_rate" xorm:"rate"`           //正确率
	State    int    `json:"exam_state" xorm:"state"`         //状态 0 继续答题 1 交卷已完成
	UpdateAt int64  `json:"exam_update_at" xorm:"update_at"` //更新时间
	At       int64  `json:"exam_at" xorm:"at"`               //创建时间
}

func (this *ExamLog) TableName() string {
	return "exam_log"
}
func (this *ExamLog) Save() (int64, error) {
	this.At = time.Now().Unix()
	this.UpdateAt = time.Now().Unix()
	return Db(0).Insert(this)
}

func (this *ExamLog) Get() (bool, error) {
	return Db(0).Get(this)
}

func (this *ExamLog) Count(where string) (int64, error) {
	return Db(0).Where(where).Count(this)
}
func (this *ExamLog) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *ExamLog) Set(field string) (int64, error) {
	where := fmt.Sprintf("sid = %d and uid = %d and nid = %d", this.SId, this.UId, this.NId)
	return this.update(where, field)
}

func (this *ExamLog) where(fage, count, page int, where, field string) ([]ExamLog, error) {
	list := make([]ExamLog, 0)
	var err error
	if field == "" {
		field = "update_at"
	}
	if 0 == fage { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *ExamLog) List(val *Pager) error {
	val.TName = this.TableName()
	w := val.ToWhere()
	val.Total, _ = this.Count(w)
	list, err := this.where(val.Rules, val.Count, val.Page-1, w, "")
	if err == nil {
		val.List = list
	}
	return err
}
